<?php

namespace App\ApiBackend\Admin;

use App\Domains\AdminDomain;
use App\Http\Controllers\ApiBaseController;
use Illuminate\Support\Facades\DB;

/**
 *  用户菜单和权限
 */
class MenuPermission extends ApiBaseController
{

  /**
   * 参数检查
   */
  protected function check(): void
  {
  }

  /**
   * 业务主体
   */
  protected function service(): void
  {
    $uid = \request()->user()['adminId'];
    $adminInfo = AdminDomain::getAdminInfo($uid);
    if (!$adminInfo) {
      $this->result['code'] = 1;
      $this->result['message'] = '用户数据获取失败';
      return;
    }
    //查询开启模块
    $moduleList = array_merge(["system"], config('module.moduleList'));
    //菜单和权限
    if (!$adminInfo->isSuper) {
      $whereArr = [
        'am.status' => 1,
        'aa.adminRoleId' => $adminInfo->adminRoleId,
      ];
      $roleMenu = DB::table("admin_role_menu as aa")
        ->join("admin_menu as am", 'am.id', '=', 'aa.adminMenuId')
        ->select(['am.id', 'am.pids'])
        ->where($whereArr)
        ->whereIn('am.module', $moduleList)
        ->get();
      $menuIdArr = [];
      foreach ($roleMenu as $item) {
        if ($item->pids) {
          $menuIdArr = array_merge($menuIdArr, explode(",", $item->pids));
        }
        $menuIdArr[] = $item->id;
      }
      //部分账号开放权限 start
      // $adminIdArr = [
      //     30,//测试
      // ];
      // if (in_array($uid, $adminIdArr)) {
      //     $menuIdArr[] = 42;
      //     $menuIdArr[] = 56;
      // }
      $menuIdArr = array_unique($menuIdArr);
      // 菜单
      $roleMenuList = DB::table("admin_menu as aa")
        ->where('status', 1)
        ->whereIn("id", $menuIdArr)
        ->orderBy("type", 'ASC')
        ->orderBy("orderNo")
        ->get();

    } else {
      $roleMenuList = DB::table("admin_menu as aa")
        ->where('aa.status', 1)
        ->whereIn('aa.module', $moduleList)
        ->orderBy("type", 'ASC')
        ->orderBy("orderNo")
        ->get();
    }
    // dump($roleMenuList);
    //菜单和权限
    $permissionArr = [];
    $menuArr = [];
    //$roleMenuList 查询后菜单顺序必须为 一级目录 二级目录 三级菜单, 请确认orderNo 是否正确, orderNo的值:一级目录1-9 二级10-99 三级100-999
    foreach ($roleMenuList as $roleMenu) {
      if ($roleMenu->type == 2) {//权限
        $permissionArr[] = $roleMenu->perms;
        continue;
      }
      //基本路由
      $routeObj = [
        "path" => $roleMenu->path,
        "name" => $roleMenu->name,
        "component" => $roleMenu->type == 0 ? 'LAYOUT' : $roleMenu->component,
        "meta" => [
          'title' => $roleMenu->title,
        ]
      ];
      //meta处理
      ($roleMenu->isHide) && $routeObj['meta']['hideMenu'] = true;
      ($roleMenu->icon) && $routeObj['meta']['icon'] = $roleMenu->icon;
      ($roleMenu->currentActiveMenu) && $routeObj['meta']['currentActiveMenu'] = $roleMenu->currentActiveMenu;
      //目录处理
      if ($roleMenu->type == 0) {//目录处理, pid=0为一级目录 否则二级目录
        $roleMenu->pid > 0 ? $menuArr[$roleMenu->pid]['children'][$roleMenu->id] = $routeObj : $menuArr[$roleMenu->id] = $routeObj;
      } else {//菜单,  菜单添加前按照orderNo约定,上级已经添加好
        $pidArr = explode(",", $roleMenu->pids);
        if (count($pidArr) > 1) {//二级目录下菜单
          $menuArr[$pidArr[0]]['children'][$pidArr[1]]['children'][] = $routeObj;
        } else {//一级目录的菜单
          $menuArr[$pidArr[0]]['children'][] = $routeObj;
        }
      }
    }
    // dump($menuArr);
    //键值重置和设置目录跳转连接
    $j = 0;
    $menuNewArr = [];
    foreach ($menuArr as $menuOne) {
      $menuNewArr[$j] = $menuOne;
      $menuNewArr[$j]['children'] = [];
      $jj = 0;
      if (!empty($menuOne['children'])) {
        foreach ($menuOne['children'] as $menuTwo) {
          $menuNewArr[$j]['children'][$jj] = $menuTwo;
          if (empty($menuTwo['children'])) {//一级目录下是菜单(二级菜单)
            //设置目录跳转菜单
            empty($menuNewArr[$j]['redirect']) && $menuNewArr[$j]['redirect'] = $menuOne['path'] . '/' . $menuTwo["path"];
          } else {//一级目录下是目录(三级菜单)
            $jjj = 0;
            $menuNewArr[$j]['children'][$jj]['children'] = [];
            // unset($menuNewArr[$j]['children'][$jj]['component']);
            foreach ($menuTwo['children'] as $menuThree) {
              $menuNewArr[$j]['children'][$jj]['children'][$jjj] = $menuThree;
              //设置目录跳转菜单
              empty($menuNewArr[$j]['redirect']) && $menuNewArr[$j]['redirect'] = $menuOne['path'] . '/' . $menuTwo["path"] . "/" . $menuThree['path'];
              $jjj++;
            }
          }
          $jj++;
        }
      }
      $j++;
    }
    // dump($menuNewArr);
    $this->result['data']['permissionList'] = $permissionArr;
    $this->result['data']['menuList'] = $menuNewArr;
  }
}
